#include "toast.h"

#include <QApplication>
#include <QScreen>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>

Toast::Toast(const QString &text, int time)
{
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog | Qt::Tool | Qt::WindowStaysOnTopHint);
    // 1. 创建显示文本的 Label
    QLabel* label = new QLabel();
    label->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    label->setAlignment(Qt::AlignCenter);
    label->setStyleSheet("QLabel { font-size: 32px; padding: 20px 40px; }"); // 增加padding让Toast看起来更美观
    label->setText(text);

    // 2. 添加布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(label);
    this->setLayout(layout);

    // 3. 计算自适应大小
    this->adjustSize(); // 让窗口根据内容自适应

    // 4. 设置窗口参数
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QDialog { background-color: rgb(255, 255, 255); border-radius: 12px; }");
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog | Qt::Tool); // Tool 避免任务栏出现

    // 5. 计算窗口的位置, 居中靠下
    QScreen* screen = QApplication::primaryScreen();
    int width = screen->size().width();
    int height = screen->size().height();
    int winW = this->width();
    int winH = this->height();
    int x = (width - winW) / 2;
    int y = height - winH - 100; // 距离底部100像素
    this->move(x, y);

    // 6. 自动关闭
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]() {
        timer->stop();
        this->close();
    });
    timer->start(time);
}
void Toast::showMessage(const QString &text, int time)
{
    Toast* toast = new Toast(text, time);
    toast->show();
}

























